from odoo import fields, models, api
from odoo.exceptions import UserError
from ...functions.suggested_reading_time_functions import SuggestedReadingTimeFunctions as SuggestedReadingTime


class RPWebArticle(models.Model):
    _name = 'rp.suggested.reading.time'
    _description = "建议阅读时间"
    _rec_name = "name"
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '名称重复')]

    def _default_get_time(self):
        time = self.env['uom.category'].search([('name', '=', 'Working Time')])
        return [('category_id', '=', time.id if time else False)]

    def _default_get_min(self):
        cm = self.env['uom.uom'].search([('name', '=', 'Min')])
        return cm.id if cm else False

    time_uom_id = fields.Many2one(string='时间单位', comodel_name='uom.uom', required=True, domain=_default_get_time, default=_default_get_min)

    name = fields.Char(string='描述', index=True, copy=False, readonly=True, compute='_depends_fulfill_name', store=True)

    integer_form = fields.Integer(string='整数格式', required=True)
    clock_form = fields.Char(string='时钟格式', required=True)
    text_form = fields.Char(string='文本格式', required=True)

    active = fields.Boolean(string='有效', default=True)

    @api.onchange('integer_form', 'time_uom_id')
    def _onchange_fulfill_clock_and_text_form(self):
        if self.integer_form and self.time_uom_id:
            # 将整数格式转换成时钟格式和文本格式
            clock_format, text_format = SuggestedReadingTime(self).convert_to_time_and_text(self.integer_form, self.time_uom_id)
            self.update({'clock_form': clock_format, 'text_form': text_format})

    @api.depends('integer_form', 'time_uom_id')
    def _depends_fulfill_name(self):
        for s in self:
            if s.integer_form and self.time_uom_id:
                s.write({'name': '{} {}'.format(s.integer_form, s.time_uom_id.name)})
